/* global authAxios */

import Cookies from 'js-cookie'
import endPoints from './endPoints'
import { setAuthCredentials, clearCookiesOnLogout } from '../store/utils/api'

export default {
  login (creds) {
    return new Promise((resolve, reject) => {
      authAxios
        .post('api/v1/authserver/accounts/login', creds)
        .then(response => {
          setAuthCredentials(response)
          resolve(response.data)
        })
        .catch(error => {
          reject(error.response)
        })
    })
  },

  register (creds) {
    const urlData = endPoints('register')
    const fetchPromise = new Promise((resolve, reject) => {
      authAxios
        .post(urlData.url, {
          name: creds.accountName.trim(),
          fullName: creds.fullName.trim(),
          email: creds.email,
          password: creds.password,
          h_captcha_client_response: creds.hCaptchaClientResponse,
        })
        .then(response => {
          // setAuthCredentials(response)
          resolve(response)
        })
        .catch(error => {
          reject(error)
        })
    })
    return fetchPromise
  },
  validityCheck () {
    const urlData = endPoints('validityCheck')
    return authAxios.get(urlData.url)
  },
  logout () {
    const urlData = endPoints('logout')
    const fetchPromise = new Promise((resolve, reject) => {
      authAxios
        .delete(urlData.url)
        .then(response => {
          clearCookiesOnLogout()
          resolve(response)
        })
        .catch(error => {
          reject(error)
        })
    })
    return fetchPromise
  },
  hasAuthCookie () {
    const json = Cookies.getJSON('cw_d_session_info')
    return !!json
  },
  getAuthData () {
    if (this.hasAuthCookie()) {
      return Cookies.getJSON('cw_d_session_info')
    }
    return false
  },
  verifyPasswordToken ({ tenantId, userId, confirmationToken }) {
    return new Promise((resolve, reject) => {
      authAxios
        .get('api/v1/authserver/accounts/confirmAccount', { params: {
          tenantId: tenantId,
          userId: userId,
          confirmationToken: confirmationToken,
        }})
        .then(response => {
          // setAuthCredentials(response)
          resolve(response)
        })
        .catch(error => {
          reject(error.response)
        })
    })
  },

  setNewPassword ({ tenantId, userId, resetPasswordToken, password, confirmPassword }) {
    return new Promise((resolve, reject) => {
      authAxios
        .put('api/v1/authserver/accounts/setNewPassword', {
          tenantId: tenantId,
          userId: userId,
          resetPasswordToken: resetPasswordToken,
          confirmPassword: confirmPassword,
          password,
        })
        .then(response => {
          // setAuthCredentials(response)
          resolve(response)
        })
        .catch(error => {
          reject(error.response)
        })
    })
  },

  resetPassword ({ email }) {
    const urlData = endPoints('resetPassword')
    return authAxios.post(urlData.url, { email })
  },

  profileUpdate ({
    password,
    password_confirmation,
    displayName,
    avatar,
    ...profileAttributes
  }) {
    const formData = new FormData()
    Object.keys(profileAttributes).forEach(key => {
      const hasValue = profileAttributes[key] === undefined
      if (!hasValue) {
        formData.append(`${key}`, profileAttributes[key])
      }
    })
    formData.append('displayName', displayName || '')
    if (password && password_confirmation) {
      formData.append('password', password)
      formData.append('password_confirmation', password_confirmation)
    }
    if (avatar) {
      formData.append('avatar', avatar)
    }
    return authAxios.put(endPoints('profileUpdate').url, formData)
  },

  updateUISettings ({ uiSettings }) {
    return authAxios.put(endPoints('uiSettings').url, {
      uiSettings: uiSettings
    })
  },

  updateAvailability (availabilityData) {
    return authAxios.post(endPoints('availabilityUpdate').url, {
      ...availabilityData,
    })
  },

  updateAutoOffline (accountId, autoOffline = false) {
    return authAxios.post(endPoints('autoOffline').url, {
      autoOffline: autoOffline
    })
  },

  deleteAvatar () {
    return authAxios.delete(endPoints('deleteAvatar').url)
  },

  setActiveAccount ({ accountId }) {
    const urlData = endPoints('setActiveAccount')
    return authAxios.put(urlData.url, {
      profile: {
        accountId: accountId,
      },
    })
  },
}
